// @ts-ignore
import { onUnmounted, onBeforeUnmount } from 'vue';
import MescrollMixin from '@/uni_modules/mescroll-uni/mescroll-mixins.js';

export const provideKey = 'ScrollPage';

/** 在pages定义的页面组件使用该mixin */
export const pageMixins = [
  {
    provide() {
      return {
        [provideKey]: this,
      };
    },
    onPageScroll(e: any) {
      if ((this as any).mescroll) {
        (this as any).mescroll.onPageScroll(e);
      }
    },
    onReachBottom() {
      if ((this as any).mescroll) {
        (this as any).mescroll.onReachBottom();
      }
    },
    onPullDownRefresh() {
      if ((this as any).mescroll) {
        (this as any).mescroll.onPullDownRefresh();
      }
    },
  },
];

const clonedMescrollMixin = { ...MescrollMixin };

// 组件监听也会执行，此处不能监听
['onPageScroll', 'onReachBottom', 'onPullDownRefresh'].forEach(key => {
  delete clonedMescrollMixin[key];
});

/** 封装的滚动组件使用该mixin */
export const componentMixins = [
  clonedMescrollMixin,
  {
    inject: [provideKey],
    mounted() {
      if ([provideKey]) {
        ([provideKey] as any).mescroll = (this as any).mescroll;
      }
    },
    beforeUnmount() {
      if ([provideKey]) {
        ([provideKey] as any).mescroll = null;
      }
    },
  },
];
